package com.example.threaddemo.reference;

import java.lang.ref.SoftReference;

/**
 * 内存够用就不回收，不够就回收
 */
public class SoftReferenceDemo {
    public static void main(String[] args) {

//        softRef_Memory_Enough();
        softRef_Memory_Not_Enough();
    }

    private static void softRef_Memory_Enough() {
        Object obj1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(obj1);
        System.out.println("********GC 前***********");
        System.out.println(obj1);
        System.out.println(softReference.get());

        System.out.println("********GC 后***********");
        obj1 = null;
        System.gc();
        System.out.println(obj1);
        System.out.println(softReference.get());

    }

    /**
     * JVM 配置，故意产生大对象，并配置小内存，让它内存不够用了导致OOM，看软引用
     * -Xms5m -Xmx5m -XX:+PrintGCDetails
     */
    private static void softRef_Memory_Not_Enough() {
        Object obj1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(obj1);
        System.out.println("******** OOM GC 前***********");
        System.out.println(obj1);
        System.out.println(softReference.get());

        obj1 = null;
//        System.gc();
        System.out.println("******** OOM  GC 后***********");
        try {
            byte[] bytes = new byte[30 * 1024 * 1024];
            System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
        } catch (Throwable e) {
            System.out.println("内存溢出了");
            e.printStackTrace();
        } finally {
            System.out.println("finally--");
            System.out.println(obj1);
            System.out.println(softReference.get());
        }
    }
}
